<?php

namespace app\admin\controller;

use function MongoDB\BSON\toJSON;
use think\Db;
use clt\Leftnav;
use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\authRule;
use think\facade\Request;
use think\Validate;

class Auth extends Common
{
    /**
     * @return array|mixed
     * 设备列表
     */
    public function devList()
    {
        if (request()->isPost()) {
            $key = input('post.key') ? input('key') : '';
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $list = Db('nyd_dev')
                ->alias('a')
                ->join('nyd_gateway b','a.gateway_id = b.id')
                ->join('nyd_house c','b.house_id = c.id')
                ->join('nyd_control_dev g','g.id = a.control_id')
                ->field('a.id,a.dev_name,a.dev_mac,g.control_id,b.gateway_name,c.house_name,a.is_bad,a.is_open,a.is_del,b.gateway_id')
                ->where('a.is_del', 1)
                ->where('a.dev_name|a.dev_mac', 'like', "%" . $key . "%")
                ->paginate(array('list_rows' => $pageSize, 'page' => $page))
                ->toArray();

            foreach ($list['data'] as $k => $v) {
                if ($list['data'][$k]['is_bad'] == 1) {
                    $list['data'][$k]['is_bad'] = '正常';
                } else if ($list['data'][$k]['is_bad'] == 2) {
                    $list['data'][$k]['is_bad'] = '故障';
                }
            }
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        return $this->fetch('dev_list');
    }

    /**
     * 添加设备
     */
    public function devAdd()
    {

        if (request()->isAjax()) {
            if (empty(input('post.control_id'))) {
                if (!empty(input('post.house_id'))) {
                    $house_id = input('post.') ? input('post.') : '';
                    //网关
                    $gateway = Db::name('nyd_gateway')->where('house_id', $house_id['house_id'])->select();

                    return $gateway;
                }
                if (!empty(input('post.gateway_id'))) {

                    $gateway_id = input('post.');
                    $control = Db::name('nyd_control_dev')->where('gateway_id',$gateway_id['gateway_id'])->select();
                    return $control;
                }
            } else {
                if (request()->isPost()) {
                    $data = input('post.');

                    if($data['gateway_id']==-1){
                        $this->error('添加失败');
                    }
                    $dev_mac = $data['dev_mac'];
                    $res = Db::name('nyd_dev')
                        ->where('is_del', 1)
                        ->where('dev_mac', $dev_mac)
                        ->select();
                    if ($res) {
                        return $this->error("该设备已存在");
                    } //插入设备
                    else {
                        $re = Db::name('nyd_dev')->insert($data);
                        if ($re) {
                            $this->success('添加成功');
                        } else {
                        }
                        $this->error('添加失败');
                    }
                }
            }
        }
        //选择大棚
        $house = Db::name('nyd_house')
            ->field('house_name,id')
            ->select();
        $this->assign('house', $house);

        return $this->fetch('add_dev');

    }

    /**
     * 删除设备
     */
    public function devDel()
    {
        $id = input('post.id');
        if (empty($id)) {
            return $this->error('设备不存在!');
        }
        $is_del = 2;
        db('nyd_dev')->where('id', $id)->update(['is_del' => $is_del]);
        return $this->success('设备删除成功');
    }

    /**
     * 设备状态开关
     */
    public function devState()
    {
        $id = input('post.id');
        $is_open = input('post.is_open');
        if (empty($id)) {
            return $this->error('设备不存在!');
        }
        db('nyd_dev')->where('id', $id)->update(['is_open' => $is_open]);
        return $this->success('设备状态修改成功');
    }

    /**
     * @return mixed|void
     * bianji
     */
    public function devEdit()
    {

        if (request()->isAjax()) {
            if (empty(input('post.control_id'))) {
                if (!empty(input('post.house_id'))) {
                    $house_id = input('post.') ? input('post.') : '';
                    //网关
                    $gateway = Db::name('nyd_gateway')->where('house_id', $house_id['house_id'])->select();

                    return $gateway;
                }
                if (!empty(input('post.gateway_id'))) {

                    $gateway_id = input('post.');
                    $control = Db::name('nyd_control_dev')->where('gateway_id',$gateway_id['gateway_id'])->select();
                    return $control;
                }
            } else {
                if (request()->isPost()) {
                    $data = input('post.');

                    if($data['gateway_id']==-1){
                        $this->error('修改失败，请填写有效网关');
                    }
                    $re = Db::name('nyd_dev')->where('id', $data['id'])->update($data);
                    if ($re) {
                        $this->success('修改成功');
                    } else {
                        $this->error('修改失败');
                    }

                }
            }
        }
        $id = input('get.id');
        if (empty($id)) {
            return $this->error('设备不存在!');
        }
        $result = Db::name('nyd_dev')
            ->alias('a')
            ->join('nyd_gateway b','a.gateway_id = b.id')
            ->join('nyd_house c','b.house_id = c.id')
            ->join('nyd_control_dev g','g.id = a.control_id')
            ->field('a.id,a.dev_name,a.dev_mac,a.control_id,g.control_longname,b.gateway_name,c.house_name,a.is_bad,a.is_open,a.is_del,a.gateway_id, c.id k')
            ->where('a.is_del', 1)
            ->where('a.id', $id)
            ->find();
        //选择大棚
        $house = Db::name('nyd_house')
            ->field('house_name,id')
            ->select();
        $this->assign('house', $house);
        $this->assign('info', $result);
        $this->assign('id', $id);
        return $this->fetch('dev_edit');
    }










    /********************************权限管理*******************************/
    public function adminRule()
    {
        if (request()->isPost()) {
            $arr = cache('authRuleList');
            if (!$arr) {
                $arr = Db::name('authRule')->order('pid asc,sort asc')->select();
                foreach ($arr as $k => $v) {
                    $arr[$k]['lay_is_open'] = false;
                }
                cache('authRuleList', $arr, 3600);
            }
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $arr, 'is' => true, 'tip' => '操作成功'];
        }
        return view();
    }

    public function clear()
    {
        $arr = Db::name('authRule')->where('pid', 'neq', 0)->select();
        foreach ($arr as $k => $v) {
            $p = Db::name('authRule')->where('id', $v['pid'])->find();
            if (!$p) {
                Db::name('authRule')->where('id', $v['id'])->delete();
            }
        }
        cache('authRule', NULL);
        cache('authRuleList', NULL);
        $this->success('清除成功');
    }

    public function ruleAdd()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['addtime'] = time();
            authRule::create($data);
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            cache('addAuthRuleList', NULL);
            return $result = ['code' => 1, 'msg' => '权限添加成功!', 'url' => url('adminRule')];
        } else {
            $nav = new Leftnav();
            $arr = cache('addAuthRuleList');
            if (!$arr) {
                $authRule = authRule::all(function ($query) {
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('addAuthRuleList', $arr, 3600);
            }
            $this->assign('admin_rule', $arr);//权限列表
            return $this->fetch();
        }
    }

    public function ruleOrder()
    {
        $auth_rule = db('auth_rule');
        $data = input('post.');
        if ($auth_rule->update($data) !== false) {
            cache('authRuleList', NULL);
            cache('authRule', NULL);
            cache('addAuthRuleList', NULL);
            return $result = ['code' => 1, 'msg' => '排序更新成功!', 'url' => url('adminRule')];
        } else {
            return $result = ['code' => 0, 'msg' => '排序更新失败!'];
        }
    }

    //设置权限菜单显示或者隐藏
    public function ruleState()
    {
        $id = input('post.id');
        $menustatus = input('post.menustatus');
        if (db('auth_rule')->where('id=' . $id)->update(['menustatus' => $menustatus]) !== false) {
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            cache('addAuthRuleList', NULL);
            return ['status' => 1, 'msg' => '设置成功!'];
        } else {
            return ['status' => 0, 'msg' => '设置失败!'];
        }
    }

    //设置权限是否验证
    public function ruleTz()
    {
        $id = input('post.id');
        $authopen = input('post.authopen');
        if (db('auth_rule')->where('id=' . $id)->update(['authopen' => $authopen]) !== false) {
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            cache('addAuthRuleList', NULL);
            return ['status' => 1, 'msg' => '设置成功!'];
        } else {
            return ['status' => 0, 'msg' => '设置失败!'];
        }
    }

    public function ruleDel()
    {
        $id = input('post.id');
        $this->delauth($id);
        cache('authRule', NULL);
        cache('authRuleList', NULL);
        cache('addAuthRuleList', NULL);
        return $result = ['code' => 1, 'msg' => '删除成功!'];
    }

    function delauth($id)
    {
        AuthRule::destroy($id);
        $authSon = Db::name('auth_rule')->where('pid', $id)->select();
        if (!empty($authSon)) {
            foreach ($authSon as $k => $v) {
                $this->delauth($v['id']);
            }
        }
        return true;
    }

    public function ruleEdit()
    {
        if (request()->isPost()) {
            $datas = input('post.');
            if (authRule::update($datas)) {
                cache('authRule', NULL);
                cache('authRuleList', NULL);
                cache('addAuthRuleList', NULL);
                return json(['code' => 1, 'msg' => '保存成功!', 'url' => url('adminRule')]);
            } else {
                return json(['code' => 0, 'msg' => '保存失败！']);
            }
        } else {
            $admin_rule = authRule::get(function ($query) {
                $query->where(['id' => input('id')])->field('id,href,title,icon,sort,menustatus');
            });
            $this->assign('rule', $admin_rule);
            return $this->fetch();
        }
    }
}